package com.chenzouquan.util;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.opencsv.CSVWriter;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class JsonToCsvConverter {
    String jsonFilePath = "path/to/json/file.json"; // JSON文件路径
    String csvFilePath = "path/to/csv/file.csv"; // 要保存的CSV文件路径


    /**
     * JSON转CSV函数
     * @param jsonFilePath
     * @param csvFilePath
     */
    public boolean  change(String jsonFilePath, String csvFilePath) {

        try {
            // 创建ObjectMapper对象
            ObjectMapper objectMapper = new ObjectMapper();

            // 读取JSON文件并解析为JsonNode对象
            JsonNode jsonNode = objectMapper.readTree(new File(jsonFilePath));
            JsonNode data = jsonNode.get("data");
            // 消除之前添加的主节点
            if (data != null){
                jsonNode = data;
            }
            // 创建CSV文件写入器
            FileWriter csvFileWriter = new FileWriter(csvFilePath);
            CSVWriter csvWriter = new CSVWriter(csvFileWriter);

            // 获取JSON数组的所有属性字段
            Iterator<JsonNode> elements = jsonNode.elements();
            List<String> headerList = new ArrayList<>();

            // 从第一个JSON对象获取表头字段
            if (elements.hasNext()) {
                JsonNode firstObject = elements.next();
                Iterator<String> fieldNames = firstObject.fieldNames();
                while (fieldNames.hasNext()) {
                    headerList.add(fieldNames.next());
                }
            }

            // 写入CSV文件的表头
            csvWriter.writeNext(headerList.toArray(new String[0]));

            // 遍历JSON数组并将每个属性值写入CSV文件
            while (elements.hasNext()) {
                JsonNode object = elements.next();
                List<String> valueList = new ArrayList<>();
                for (String header : headerList) {
                    String value = object.get(header).asText();
                    valueList.add(value);
                }
                csvWriter.writeNext(valueList.toArray(new String[0]));
            }
            csvWriter.close();
            // 删除原文件
            new File("jsonFilePath").delete();
            // 关闭CSVPrinter和FileWriter
            System.out.println("JSON转换为CSV成功");
            // 删除原文件
            new File(jsonFilePath).delete();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 删除原文件
        new File(jsonFilePath).delete();
        return false;
    }
}
